package com.example.task;

import com.example.mapper.OrderMapper;
import com.example.mapper.RoomMapper;
import com.example.pojo.Order;
import com.example.service.Impl.OrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class autoReleaseRoom {
    @Resource
    private OrderService orderService;
    @Resource
    private RoomMapper roomMapper;

    // 每30分钟执行一次检查
    @Scheduled(cron = "0 0/30 * * * ? ")
    public void autoReleaseRoom() {
        log.info("开始检查超时未确认的订单...");


        //TODO
        //1. 查询所有状态为1的订单（状态1-已支付，创建时间超过15分钟）
        List<Order> orders = orderService.selectAllByStatusAndTime("1",60*15);
        // 2. 处理每个超时订单
        orders.forEach(order -> {
            log.info("订单： {} 超时未确认，触发重新上架房间", order.getId());
            // 3. 更新订单状态为4（已取消）
            order.setStatus("4");
            orderService.cancelOrder(order.getId());
            // 4. 更新房间状态为0（空闲）
            roomMapper.updateStatus(order.getRoomId(), "0");
        });

        log.info("释放了{}个超时订单", orders.size());

    }
}
